package com.cross.jdbc;

import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.dom4j.DocumentException;

import com.cross.core.AbstractWriter;
import com.cross.core.Column;
import com.cross.core.Header;
import com.cross.test.util.DataBaseHelper;
import com.cross.util.ItemType;
/**
 * jdbc写入器
 * @author www
 *
 */
public class SimpleJdbcWriter extends AbstractWriter {
	//数据表名
	private String table;
	//预处理语句
	private PreparedStatement preparedStatement;
	//数据库连接
	private Connection con;
	
	/**
	 * 构造方法
	 * @param table
	 * @param header
	 * @throws FileNotFoundException
	 * @throws DocumentException
	 * @throws SQLException
	 */
	public SimpleJdbcWriter(String table, Header header)  throws FileNotFoundException,
		DocumentException, SQLException {
		this.table = table;
		this.setHeader(header);
		init();
	}
	/**
	 * 写入一行
	 */
	@Override
	protected void writeRow() {
		try {
			writeRowImpl();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 写入一行
	 * @throws SQLException
	 */
	private void writeRowImpl() throws SQLException{
		String type ;
		long parameterIndex = 0;
		for(Column c : header.getColumns()){
			type = c.getType();
			if(ItemType.TYPE_STRING.equals(type)){
				preparedStatement.setString((int)parameterIndex+1, currentRow.getItem(parameterIndex).getString());
			} else if(ItemType.TYPE_NUMBER.equals(type)){
				preparedStatement.setInt((int)parameterIndex+1, currentRow.getItem(parameterIndex).getInteger());
			}
			//TODO 
			parameterIndex++;
		}
		preparedStatement.execute();
	}
	
	/**
	 * 关闭
	 */
	@Override
	public void close() {
		try {
			con.commit();
			preparedStatement.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化
	 * @throws FileNotFoundException
	 * @throws DocumentException
	 * @throws SQLException
	 */
	private void init() throws FileNotFoundException, DocumentException,
			SQLException {
		con = DataBaseHelper.getDbConnection("one");
		preparedStatement = con.prepareStatement(getPreparedStatement(header));
	}

	/**
	 * 根据header获得一个预处理sql
	 * @param header
	 * @return
	 */
	private String getPreparedStatement(Header header) {
		StringBuffer sql = new StringBuffer();
		StringBuffer temp = new StringBuffer();
		sql.append("insert into ").append(table).append(" ( ");
		temp.append(" (");
		List<Column> columns = header.getColumns();
		for (Column c : columns) {
			sql.append(c.getTitle());
			sql.append(", ");
			temp.append("?, ");
		}
		sql.replace(sql.lastIndexOf(","), sql.length(), " ) values ");
		temp.replace(temp.lastIndexOf(","), temp.length(), " ) ");
		sql.append(temp);

		return sql.toString();
	}
}
